package com.cheyun.netsalev3

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.os.Build
import android.os.Bundle
import android.view.WindowManager
import android.webkit.WebView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.alibaba.sdk.android.oss.ClientConfiguration
import com.alibaba.sdk.android.oss.OSS
import com.alibaba.sdk.android.oss.OSSClient
import com.alibaba.sdk.android.oss.common.OSSLog
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider
import com.cheyun.netsalev3.utils.AppCongfig
import com.cheyun.netsalev3.tencenttim.chat.ChatActivity
import com.cheyun.netsalev3.tencenttim.helper.CustomAVCallUIController
import com.cheyun.netsalev3.tencenttim.helper.CustomMessage
import com.cheyun.netsalev3.tencenttim.utils.DemoLog
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.api.BaseResp
import com.cheyun.netsalev3.view.AddClueActivity
import com.cheyun.netsalev3.view.MainActivity
import com.cheyun.netsalev3.view.TimChatActivity
import com.cheyun.netsalev3.view.WelComeActivity
import com.cheyunkeji.er.app.UserInfoManager
import com.cheyunkeji.er.bean.CarIds
import com.cheyunkeji.er.bean.evaluate.CarTempAttrList
import com.cheyunkeji.er.bean.evaluate.EvaluateDetailResult2
import com.cheyunkeji.er.http.HttpConstants
import com.cheyunkeji.er.service.OssService
import com.cheyunkeji.er.utils.SerializeUtil
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.imsdk.*
import com.tencent.qcloud.tim.uikit.base.IMEventListener
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
//import com.pgyer.pgyersdk.PgyerSDKManager


/**
 * @author
 * @date  2018/11/2 - 11:33.
 */
class MyApplication : Application() {
    // activity堆栈
    private var activityList = ArrayList<AppCompatActivity>()
    private var chatActivity: ChatActivity? = null;
    private var timOffLine: Boolean = false
    private var timBusying: Boolean = false

    var app_version: String = ""

    private val TAG = MyApplication::class.java!!.getSimpleName()

    public var enableShowMsg = false

//    private var waitTimMsg: List<TIMMessage>? = null

    public var atAddClueActivity: Boolean = false
    public var atChatActivity: Boolean = false

    override fun onCreate() {
        super.onCreate()
        mInstance = this
        getHightWidth()


        app_version = FunctionUtils.getCurrentCode(this)

        var formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)
                .methodCount(0)
                .tag("MyTag")
                .build()
        Logger.addLogAdapter(AndroidLogAdapter(formatStrategy))

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            var processName = getProcessName(this)
//            var packageName = this.getPackageName()
//            if (!packageName.equals(processName)) {
//                WebView.setDataDirectorySuffix(processName)
//            }
            WebView.setDataDirectorySuffix(processName)
        }

        //二手车
        car300Ids = CarIds()
        OSSLog.enableLog()

//        PgyerSDKManager.Init()
//                .setContext(this) //设置上下问对象
//                .start()
    }



    fun getProcessName(context: Context): String {
        if (context == null) return ""
        var manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (processInfo in manager.runningAppProcesses) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName
            }
        }
        return ""
    }

    override fun onConfigurationChanged(newConfig: Configuration?) {
        if (newConfig?.fontScale != 1f)//非默认值
            getResources()
        super.onConfigurationChanged(newConfig)
    }

    override fun getResources(): Resources {
        val res = super.getResources()
        if (res.configuration.fontScale != 1f) {//非默认值
            val newConfig = Configuration()
            newConfig.setToDefaults()//设置默认
            res.updateConfiguration(newConfig, res.displayMetrics)
        }
        return res
    }

    private fun getHightWidth() {
        val wm = this
                .getSystemService(Context.WINDOW_SERVICE) as WindowManager
        AppCongfig.width = wm.defaultDisplay.width
        AppCongfig.height = wm.defaultDisplay.height
    }

    /**
     * 添加activity
     */
    fun addActivity(activity: AppCompatActivity) {
        if (activity is AddClueActivity) {
            atAddClueActivity = true
        } else {
            atAddClueActivity = false
        }
        if (activity is TimChatActivity) {
            atChatActivity = true
        } else {
            atChatActivity = false
        }
        activityList.add(activity)
    }

    fun removeActivity(clas: Class<*>) {
        for (index in activityList.size - 1 downTo 0) {
            var i = activityList.get(index)
            if (clas.isInstance(i)) {
                activityList.removeAt(index);
                if (clas.equals(AddClueActivity::class.java)) {
                    atAddClueActivity = false
                }
                if (clas.equals(TimChatActivity::class.java)) {
                    atChatActivity = false
                }
            }
        }
    }

    /**
     * 获取activity列表
     */
    fun getAcitvitys(): ArrayList<AppCompatActivity> {
        return activityList
    }

//    fun getThirdCode(): String {
//        return thirdCode
//    }

    fun addChatActivity(activity: ChatActivity) {
        chatActivity = activity
    }

    fun getTimAcitvitys(): ChatActivity? {
        return chatActivity
    }

    fun setTimOffline(flag: Boolean) {
        timOffLine = flag
    }

    fun getTimOffline(): Boolean {
        return timOffLine
    }

    fun setTimBusying(flag: Boolean) {
        timBusying = flag
    }

    fun getTimBusying(): Boolean {
        return timBusying
    }

    /**
     * 关闭除当前以外acitivity
     */
    fun initAcitvitys(clas: Class<*>) {
        for (i in activityList) {
            if (!clas.isInstance(i)) {
//                activityList.remove(i);
                i.finish()
            }
        }
    }

    /**
     * 请求错误通知
     */
    fun registerEventBus() {
        var observer = Observer<BaseResp<*>> {
            if (it.skey == "authover") {
                var isMian = false;
                var vs = MyApplication.getInstance().getAcitvitys()
                if (vs.size > 0) {
                    var currentActivity = vs.get(vs.size - 1)//.javaClass.equals(MainActivity.class)
                    if (MainActivity::class.java.isInstance(currentActivity)) {
                        isMian = true
                    }
                }
                //跳转登陆
                if (!isMian) {
                    val i2 = Intent(this, MainActivity::class.java)
                    i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    i2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    startActivity(i2)
                }
            }
            if (!it.skey.equals("api.v4.login.mobile.channel")) {
                Toast.makeText(this, it.msg, Toast.LENGTH_LONG).show()
            }
        }
        LiveEventBus.get().with("ApiCallback", BaseResp::class.java).observeForever(observer)
    }


    companion object {
        private var mInstance: MyApplication? = null
        @JvmStatic
        fun getInstance() = mInstance!!
    }

    internal inner class StatisticActivityLifecycleCallback : Application.ActivityLifecycleCallbacks {
        private var foregroundActivities = 0
        private var isChangingConfiguration: Boolean = false
        private val mIMEventListener = object : IMEventListener() {
            override fun onNewMessages(msgs: List<TIMMessage>?) {
                if (CustomMessage.convert2VideoCallData(msgs) != null) {
                    // 会弹出接电话的对话框，不再需要通知
                    CustomAVCallUIController.getInstance().onNewMessage(msgs)
                    return
                }
                for (msg in msgs!!) {
                    // 小米手机需要在设置里面把demo的"后台弹出权限"打开才能点击Notification跳转。TIMOfflinePushNotification后续不再维护，如有需要，建议应用自己调用系统api弹通知栏消息。
                    val notification = TIMOfflinePushNotification(this@MyApplication, msg)
                    notification.doNotify(this@MyApplication, R.drawable.default_user_icon)
                }
            }
        }

        override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
            DemoLog.i(TAG, "onActivityCreated bundle: " + bundle)
            if (bundle != null) { // 若bundle不为空则程序异常结束
                // 重启整个程序
                val intent = Intent(activity, WelComeActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(intent)
            }
        }

        override fun onActivityStarted(activity: Activity) {
            foregroundActivities++
            if (foregroundActivities == 1 && !isChangingConfiguration) {
                // 应用切到前台
                DemoLog.i(TAG, "application enter foreground")
                TIMManager.getInstance().doForeground(object : TIMCallBack {
                    override fun onError(code: Int, desc: String) {
                        DemoLog.e(TAG, "doForeground err = $code, desc = $desc")
                    }

                    override fun onSuccess() {
                        DemoLog.i(TAG, "doForeground success")
                    }
                })
//                TUIKit.removeIMEventListener(mIMEventListener)

            }
            isChangingConfiguration = false
        }

        override fun onActivityResumed(activity: Activity) {

        }

        override fun onActivityPaused(activity: Activity) {

        }

        override fun onActivityStopped(activity: Activity) {
            foregroundActivities--
            if (foregroundActivities == 0) {
                // 应用切到后台
                DemoLog.i(TAG, "application enter background")
                var unReadCount = 0
                val conversationList = TIMManager.getInstance().conversationList
                for (timConversation in conversationList) {
                    unReadCount += timConversation.unreadMessageNum.toInt()
                }
                val param = TIMBackgroundParam()
                param.c2cUnread = unReadCount
                TIMManager.getInstance().doBackground(param, object : TIMCallBack {
                    override fun onError(code: Int, desc: String) {
                        DemoLog.e(TAG, "doBackground err = $code, desc = $desc")
                    }

                    override fun onSuccess() {
                        DemoLog.i(TAG, "doBackground success")
                    }
                })
                // 应用退到后台，消息转化为系统通知
//                TUIKit.addIMEventListener(mIMEventListener)
            }
            isChangingConfiguration = activity.isChangingConfigurations
        }

        override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {

        }

        override fun onActivityDestroyed(activity: Activity) {

        }
    }

    //二手车

    private var car300Ids: CarIds? = null
    private var ossService: OssService? = null
    private var oss: OSS? = null
    //   缓存车辆字段列表数据
    private var attrList: CarTempAttrList? = null
    //   缓存车辆字段列表数据
    //    private static CarBasicInfoList basicList = null;
    //    缓存评估结果
    private var evaluateResult: EvaluateDetailResult2? = null

    fun getOssService(listener: OssService.onImageProcessedResultListener?): OssService {
        if (null == ossService) {
            synchronized(MyApplication::class.java) {
                ossService = OssService(getOss(), HttpConstants.ALIYUN_OSS_BUCKET, listener)
            }
        }
        ossService?.setOnImageProcessedResultListener(listener)
        return ossService!!
    }

    fun getOss(): OSS {
        if (null == oss) {
            synchronized(MyApplication::class.java) {
                val credentialProvider = OSSPlainTextAKSKCredentialProvider(HttpConstants.OSS_ACCESS_KEYID, HttpConstants.OSS_ACCESS_KEY_SECRET)
                val conf = ClientConfiguration()
                conf.connectionTimeout = 15 * 1000 // 连接超时，默认15秒
                conf.socketTimeout = 15 * 1000 // socket超时，默认15秒
                conf.maxConcurrentRequest = 5 // 最大并发请求书，默认5个
                conf.maxErrorRetry = 2 // 失败后最大重试次数，默认2次
                oss = OSSClient(getInstance().applicationContext, HttpConstants.OSS_END_POINT, credentialProvider, conf)
            }
        }
        return oss!!
    }

    fun getCar300Ids(): CarIds {
        return car300Ids!!
    }

    var hasCheckVersion = false

    fun getCarTempAttrList(): CarTempAttrList {
        return if (null == attrList) {
            SerializeUtil.getCarTempAttrList()
        } else attrList!!
    }

    fun setAttrList(attrList: CarTempAttrList) {
        this.attrList = attrList
    }

    fun getEvaluateResult(): EvaluateDetailResult2? {
        return evaluateResult
    }

    fun setEvaluateResult(evaluateResult: EvaluateDetailResult2) {
        this.evaluateResult = evaluateResult
    }

    /**
     * 清除评估结果
     */
    fun clearEvaluateResult() {
        this.evaluateResult = null
        SerializeUtil.clearEvaluateDetailResult()
    }

    fun getCurrentModuleType(): Int {
        return UserInfoManager.getInstance(getInstance()).currentModuleType
    }

    fun setCurrentModuleType(currentModuleType: Int) {
        UserInfoManager.getInstance(getInstance()).saveCurrentModuleType(currentModuleType)
    }
}